package com.cloudcentral.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.cloudcentral.entity.Platform;
import com.cloudcentral.mapper.PlatformBaseMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.Duration;
import java.util.Arrays;

import static com.cloudcentral.util.Utils.errorMessage;

/**
 * Create by Administrator
 * 2023/11/15 10:50
 */
@Slf4j
@Controller
@Tag(name = "视图内容")
public class ViewController {
  private final PlatformBaseMapper platformBaseMapper;
  private final RedissonClient redissonClient;

  @Autowired
  public ViewController(PlatformBaseMapper platformBaseMapper, RedissonClient redissonClient) {
    this.platformBaseMapper = platformBaseMapper;
    this.redissonClient = redissonClient;
  }

  @GetMapping("/captcha")
  @Operation(summary = "图形验证码（查询参数）", parameters = {
      @Parameter(name = "id", description = "图形验证码ID", example = "test", required = true),
      @Parameter(name = "size", description = "尺寸: width_height, 默认100_40, 最小50_20, 最大200_80", example = "100_40"),
  })
  public void captcha(@RequestParam String id, @RequestParam(required = false) String size, HttpServletResponse response) {
    long[] defaultSize = new long[]{100, 40},
        maxSize = Arrays.stream(defaultSize).map(n -> n * 2).toArray(),
        minSize = Arrays.stream(defaultSize).map(n -> n / 2).toArray();
    long[] sizeArray = StringUtils.isBlank(size) ? defaultSize : Arrays.stream(size.split("_")).mapToLong(Long::valueOf).toArray();
    long width = Math.max(Math.min(maxSize[0], sizeArray[0]), minSize[0]), height = Math.max(Math.min(maxSize[1], sizeArray[1]), minSize[1]);
    //定义图形验证码的长、宽、验证码字符数、干扰元素个数
    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha((int) width, (int) height, 4, 10);
    // 验证码值
    String code = lineCaptcha.getCode();
    redissonClient.getBucket(id).set(code, Duration.ofMinutes(1));
    log.info("生成图形验证码: {}, id: {}, size: {}_{}", code, id, width, height);
    // 输出到客户端
    try (ServletOutputStream outputStream = response.getOutputStream()) {
      // 图形验证码写出，写出到流
      lineCaptcha.write(outputStream);
    } catch (Exception e) {
      log.error("图形验证码输出错误: {}", errorMessage(e));
    }
  }

  @GetMapping("/{code}/login.html")
  public String loginForPlatform(@PathVariable(required = false) String code, Model model) {
    if (StringUtils.isNotBlank(code)) {
      Platform platform = platformBaseMapper.getByCode(code);
      if (platform == null || !platform.getEnable()) return "forward:/login.html";
      else {
        model.addAttribute("name", platform.getName());
        model.addAttribute("code", platform.getCode());
        model.addAttribute("uri", platform.getUri());
        model.addAttribute("icon", platform.getIcon());
        model.addAttribute("cover", platform.getCover());
        return "login";
      }
    } else return "forward:/login.html";
  }

  @GetMapping("/login.html")
  public String login() {
    return "login";
  }

  @GetMapping("/consent.html")
  public String consent() {
    return "consent";
  }
}
